#include "fifo.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/**
 * 函数：模拟FIFO（先进先出）页面置换算法。
 *
 * @param queue_frames 一个字符串，表示页面访问序列。
 *                     字符串中的每个字符是一个数字，表示一个页面号。
 * @param num_frames   页框的数量，表示物理内存中可用的页框数。
 */
void
fifo_page_replacement (char *queue_frames, int num)
{
  int *frames = (int*)calloc(num, sizeof(int));
  int *access_time_array = (int*)calloc(num, sizeof(int));
  int access_time = 0;
  memset(frames, -1, num * sizeof(int));

  for (char *ch = queue_frames; *ch; ch++) {
    if (*ch == ',') {
      continue;
    }
    access_time++;
    int current_frame = (int)(*ch - '0');
    int has_frame = 0;

    // Check if frame exists
    for (int i = 0; i < num; i++) {
      if (current_frame == frames[i]) {
        has_frame = 1;
        break;
      }
    }

    // Frame doesn't exist, insert frame
    if (!has_frame) {
      int first_frame = 0;
      for (int i = 1; i < num; i++) {
        if (access_time_array[i] < access_time_array[first_frame]) {
          first_frame = i;
        }
      }
      frames[first_frame] = current_frame;
      access_time_array[first_frame] = access_time;
    }

    printf("Access:%d,Frames: [", current_frame);
    for (int i = 0; i < num; i++) {
      printf("%d%s", frames[i], (i != num - 1 ? "," : "]\n"));
    }
  }
}
